package com.java202411.service;


import com.java202411.entity.FileEntity;
import com.java202411.repository.FileRepository;
import com.java202411.repository.client.MinioHTTPClient;
import io.minio.errors.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class FileService {
    private final MinioHTTPClient minioRepository;
    private final FileRepository fileRepository;

    @Value("${minio.bucket.name}")
    private String bucketName;

    public FileEntity uploadFile(String fileName, String contentType, InputStream inputStream) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        String fileCode = RandomStringUtils.randomAlphanumeric(20);
        String url = minioRepository.saveFile(bucketName, fileCode, contentType, inputStream);
        FileEntity fileEntity = fileRepository.save(
                FileEntity.builder()
                        .code(fileCode)
                        .name(fileName)
                        .contentType(contentType)
                        .createdAt(LocalDateTime.now())
                        .updatedAt(LocalDateTime.now())
                        .build()
        );
        fileEntity.setFileDownloadUrl(url);
        return fileEntity;
    }
}
